package com.example.ota_ble.ble.ota.ble

import com.example.ota_ble.ble.ota.mcu.OPCODE_DEU
import com.example.ota_ble.ble.ota.mcu.parseNotify
import com.example.ota_ble.crc.CRC32
import com.example.ota_ble.crc.crc16
import kotlin.experimental.xor

/**
 *          蓝牙OTA管理者
 *      开始，数据发送，结束等等
 * */

object ota_mcu_manager {
    var TAG = "rocjan.mcu_build_sendData"

      fun build_send_ctrl_page(pkt: ByteArray,opcode : Byte,load:ByteArray)
    {
        pkt[0] =   (parseNotify.protof_head and 0xff.toUByte() ).toByte()
        pkt[1] =   opcode
        pkt[2] =   (load.size and 0xff).toByte()
        pkt[3] =   ((load.size shr 8 )and 0xff).toByte()
        load.copyInto(pkt, 4)
        var crc16: UShort = crc16.calculateCRC16(load, load.size)

        pkt[pkt.size - 3] = (crc16.toInt()  and 0xff ).toByte()
        pkt[pkt.size - 2] = (crc16.toInt()  shr 8 and 0xff ).toByte()
        pkt[pkt.size - 1] =  (parseNotify.protof_tail and 0xff.toUByte() ).toByte()
    }
    fun build_send_data_page(pkt: ByteArray,add:Int,size:Int,load:ByteArray)
    {
        pkt[0] = (add and 0xff).toByte()
        pkt[1] = ((add shr 8) and 0xff).toByte()
        pkt[2] = ((add shr 16) and 0xff).toByte()
        pkt[3] = ((add shr 24) and 0xff).toByte()
        pkt[4] = (size and 0xff).toByte()
        pkt[5] = ((size shr 8) and 0xff).toByte()
        pkt[6] = ((size shr 16) and 0xff).toByte()
        pkt[7] = ((size shr 24) and 0xff).toByte()
        load.copyInto(pkt, 8)
        var crc16_check  = crc16.calculateCRC16(pkt, size+8)
        pkt[pkt.size - 2] = (crc16_check.toInt() and 0xff).toByte()
        pkt[pkt.size - 1] = ((crc16_check.toInt() shr 8 )and 0xff).toByte()
    }




}